import cv2
import os

from PIL import Image
def test(video_path = r'H:\抖音下载\主页作品\旗凡\视频照片二\#唱歌 “诶 国标你知道么”#天涯 #我要上热门 #旗凡.mp4', output_folder = r'H:\抖音下载\主页作品\旗凡\抽帧\#唱歌 “诶 国标你知道么”#天涯 #我要上热门 #旗凡'):
    # # 使用示例

    # # 视频文件路径
    # video_path = 'your_video.mp4'  # 替换为你的视频文件路径
    # # 输出帧的保存路径
    # output_folder = 'extracted_frames/'

    # 创建输出文件夹（如果不存在）
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    # length = cap.length   #时长 秒
    # 获取视频的帧率
    fps = cap.get(cv2.CAP_PROP_FPS)

    # 计算每隔多少帧提取一帧（每3秒提取一帧）
    frame_interval = int(fps * 3)  # 每2秒提取1帧

    count = 0
    saved_frame_count = 0

    while True:
        ret, frame = cap.read()
        if not ret:
            break  # 如果没有读取到帧，则退出

        # 每隔指定的帧数提取一帧
        if count % frame_interval == 0:
            output_filename = os.path.join(output_folder, f"frame_{saved_frame_count}.jpg")
            # cv2.imwrite(output_filename, frame)  # 保存帧为图像

            # 获取分辨率， 用于切割
            height, width, channels = frame.shape

            if height > width :
                # 计算中间区域的高度范围， 0代表最高，height 代表最低
                start_height =int(height * 1 / 3)  # 1920 * 1/3
                end_height = height  # 1920 * 2/3
                # 提取中间部分
                frame = frame[start_height:end_height, :]
            print(f"Frame Resolution: {width}x{height}")
            # 将帧转换为 PIL 图像并保存
            image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))  # 确保颜色通道正确
            image.save(output_filename)

            print(f'saved:{output_filename}')
            saved_frame_count += 1

        count += 1

    cap.release()  # 释放视频对象
    # cv2.destroyAllWindows()  # 关闭所有OpenCV窗口

    print(f"成功提取 {saved_frame_count} 帧！")
def main():
    for zhuyename in  os.listdir( r'H:\抖音下载\\'):

        path_name = f'H:\抖音下载\\{zhuyename}'
        print(path_name)

if  __name__ == "__main__":
    path = '/media/chenglei3/77D014CED257D1411/SD卡/video3/incar'
    for mp4_file in  os.listdir(path)[5:]:  # 视频路径
        # print(mp4_file)
        if mp4_file.endswith('.mp4'):
            video_path = f'{path}/{mp4_file}'  # 视频名字
            # 输出帧的保存路径
            output_folder =  f'{path}/抽帧/{mp4_file.replace(".mp4","")}'
            print('开始',video_path,output_folder)
            #
            test(video_path = video_path,output_folder = output_folder)
            # break   #临时
